package tau.dimes.config;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ConfigurationNodeBuilder
{
	public static ConfigurationNode build(Document xmlDocument)
	{
		Element documentElement = xmlDocument.getDocumentElement();

		return recursiveBuild(documentElement);
	}

	private static ConfigurationNode recursiveBuild(Element element)
	{
		ConfigurationNode configNode = new ConfigurationNode(element.getNodeName());

		NamedNodeMap attributes = element.getAttributes();
		for (int i = 0; i < attributes.getLength(); i++)
		{
			Node attributeNode = attributes.item(i);
			configNode.addAttribute(attributeNode.getNodeName(), attributeNode.getNodeValue());
		}

		NodeList children = element.getChildNodes();
		for (int i = 0; i < children.getLength(); i++)
		{
			Node childNode = children.item(i);
			if (childNode instanceof Element)
				configNode.addChild(recursiveBuild((Element) childNode));
		}

		return configNode;
	}
}
